package com.example.demo;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @program: demo
 * @description: 阿里云服务器
 * @author: yc
 * @create: 2022-11-13 15:32
 **/

public class Cshi {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static final String ACCESSKEYID = "LTAI5tPTT49QUuoCXf99tvLL";
    private static final String ACCESSKEYSERET = "zPLYsfwDiwiBP9eA2nAq81Fncz5rRb";
    // 填写Bucket名称，例如examplebucket。
    private static final String BUCKETNAME = "jinsi--siyun";
    @Test
    public void testOss() throws FileNotFoundException {
        //上传的oos的文件名称
        String objectName = "siyun/hb.jpg";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSERET);
        //创建文件流
        InputStream inputStream = new FileInputStream("C://图片/hb.jpg");
        try {
            //文件上传至oss服务器
            PutObjectResult putObjectResult = ossClient.putObject(BUCKETNAME, objectName, inputStream);
            //输出文件网络路径
            System.out.println("https://jinsi--siyun.oss-cn-beijing.aliyuncs.com/"+objectName);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
    